﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
using System.Text;
using Project362.Files;

namespace Project362.Tags
{
    public class TagHandler
    {
		private Dictionary<string,Tag> directory;
        private string fileLocation;
		public TagHandler(string fileLocation){
            this.fileLocation = fileLocation;
            if (File.Exists(fileLocation))
            {
                try
                {
                    Stream stream = File.Open(fileLocation, FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();
                    directory = (Dictionary<string, Tag>)bf.Deserialize(stream);
                    stream.Close();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                directory = new Dictionary<string, Tag>();
            }
		}
		public bool addTag(string tag){
			if(!directory.ContainsKey(tag)){
				this.directory.Add(tag,new Tag(tag));
				return true;
			}else return false;
		}
		public bool removeTag(Tag t){
			return removeTag(t.ToString());
		}
		public bool removeTag(string tag){
			if(directory.ContainsKey(tag)){
                Tag t = directory[tag];
                foreach (FileClass f in t.getFiles())
                {
                    f.removeTag(t);
                }
				this.directory.Remove(tag);
				return true;
			} else return false;
		}
		public Tag getTag(string tag){
			if(directory.ContainsKey(tag)){
				return directory[tag];
			}else return null;
		}
		public List<Tag> getList(){
			List<Tag> l=new List<Tag>();
			foreach(KeyValuePair<string,Tag> kvp in directory){
				l.Add (kvp.Value);
			}
			return l;
		}
        public bool saveTags()
        {
            try
            {
                Stream stream = File.Open(fileLocation, FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(stream, directory);
                stream.Close();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
    }
	
}
